package com.esteel.settlement.pa.service.impl;

import java.util.Date;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.esteel.settlement.entity.TbSettFund;
import com.esteel.settlement.entity.TbSettFundChg;
import com.esteel.settlement.entity.TbSettInmoney;
import com.esteel.settlement.pa.packet.InMoneyBP1310;
import com.esteel.settlement.pa.packet.PaPacket;
import com.esteel.settlement.pa.packet.RspBP1303;
import com.esteel.settlement.pa.service.PacketProcesser;
import com.esteel.settlement.service.SettFundChgService;
import com.esteel.settlement.service.SettFundService;
import com.esteel.settlement.service.SettInmoneyService;

/**
 * 入金操作指令 兼测试类
 * @author zhangxiuzhi
 *
 */
@Service
public class InMoneyProcesser extends PacketProcesser<InMoneyBP1310, RspBP1303>  {

	
	@Autowired
	private SettFundService settFundService;
	
	@Autowired
	private SettFundChgService settFundChgService;
	
	@Autowired
	private SettInmoneyService settInmoneyService;
	
	@Transactional
	public RspBP1303 execute(InMoneyBP1310 packet) {
		
		//保存数据至入金表
		TbSettInmoney tbSettInmoney = new TbSettInmoney();
		BeanUtils.copyProperties(packet, tbSettInmoney);
		
		tbSettInmoney = settInmoneyService.save(tbSettInmoney);
		
		String custAcctId = packet.getCustAcctId();
		//修改资金账户余额信息
		TbSettFund fund = settFundService.findByCustAcctId(custAcctId);
		if (fund==null){
			settFundService.syncFundInfo(custAcctId);
			fund = settFundService.findByCustAcctId(custAcctId);
		}
		
		double tranAmount = packet.getTranAmount();
		fund.setTotalAmount(fund.getTotalAmount()+tranAmount);
		fund.setTotalBalance(fund.getTotalBalance()+tranAmount);
		settFundService.save(fund);
		
		//增加账户流水信息
		TbSettFundChg settFundChg = new TbSettFundChg();
		BeanUtils.copyProperties(fund.getId(), settFundChg);
		BeanUtils.copyProperties(fund, settFundChg);
		settFundChg.setLinkType(TbSettFundChg.LinkType.IN);
		settFundChg.setLinkKey(tbSettInmoney.getInId());
		settFundChg.setTransDate(fund.getTranDate());
		settFundChg.setChgTotalAmount(tranAmount);
		settFundChg.setChgTotalBalance(tranAmount);
		settFundChgService.save(settFundChg);
		
		//组装返回数据
		RspBP1303 rsp = new RspBP1303();
		rsp.setTranFunc("1310");
		rsp.setServType(PaPacket.RESPONSE);
		rsp.setTransDate(new Date());
		rsp.setThirdLogNo("1310_"+tbSettInmoney.getInId());
		rsp.setRspCode(PaPacket.SUCCESS);
		rsp.setQydm(packet.getQydm());
		
		return rsp;
	}

	@Override
	protected String getTranFunc() {
		return "1310";
	}





}
